<?php
# 文件名称:uri.php
# MetInfo在线反馈系统 
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
defined( '_SYS' ) or die( 'No direct script access allowed' );
class C_uri {
	var	$keyval	= array();
	var $uri_string;
	var $segments		= array();
	var $rsegments		= array();
	var $permitted_uri_chars = 'a-z 0-9~%.:_\-';
	function C_uri()
	{
	}

	//处理地址栏URL
	function _fetch_uri_string()
	{		
		// 单变量
		if (is_array($_GET) && count($_GET) == 1 && trim(key($_GET), '/') != '')
		{
			$this->uri_string = key($_GET);
			return;
		}
		
		// 处理PATH_INFO变量  SELF一般为主页名index.php
		$path = (isset($_SERVER['PATH_INFO'])) ? $_SERVER['PATH_INFO'] : @getenv('PATH_INFO');
		if (trim($path, '/') != '' && $path != "/".SELF)
		{
			$this->uri_string = $path;
			return;
		}
		// 处理QUERY_STRING变量
		$path =  (isset($_SERVER['QUERY_STRING'])) ? $_SERVER['QUERY_STRING'] : @getenv('QUERY_STRING');
		if (trim($path, '/') != '')
		{
			$this->uri_string = $path;
			return;
		}
		// 处理ORIG_PATH_INFO变量
		$path = (isset($_SERVER['ORIG_PATH_INFO'])) ? $_SERVER['ORIG_PATH_INFO'] : @getenv('ORIG_PATH_INFO');
		if (trim($path, '/') != '' && $path != "/".SELF)
		{
			$this->uri_string = str_replace($_SERVER['SCRIPT_NAME'], '', $path);
			return;
		}
		$this->uri_string = '';		
	}
	//处理REQUEST_URI
	function _parse_request_uri()
	{
		if ( ! isset($_SERVER['REQUEST_URI']) OR $_SERVER['REQUEST_URI'] == '')
		{
			return '';
		}
		$request_uri = preg_replace("|/(.*)|", "\\1", str_replace("\\", "/", $_SERVER['REQUEST_URI']));
		if ($request_uri == '' OR $request_uri == SELF)
		{
			return '';
		}
		$fc_path = FCPATH;//主页绝对路径
		if (strpos($request_uri, '?') !== FALSE)
		{
			$fc_path .= '?';
		}
		$parsed_uri = explode("/", $request_uri);
		$i = 0;
		foreach(explode("/", $fc_path) as $segment)
		{
			if (isset($parsed_uri[$i]) && $segment == $parsed_uri[$i])
			{
				$i++;
			}
		}
		//将i个变量值整合
		$parsed_uri = implode("/", array_slice($parsed_uri, $i));
		if ($parsed_uri != '')
		{
			$parsed_uri = '/'.$parsed_uri;
		}
		return $parsed_uri;
	}
	//过滤
	function _filter_uri($str)
	{
		if ($str != '')
		{
			if ( ! preg_match("|^[".preg_quote($this->permitted_uri_chars)."]+$|i", $str))
			{
				//header('HTTP/1.1 400 Bad Request');
				//show_error('The URI you submitted has disallowed characters.');
			}
		}
		// 转换为 entities
		$bad	= array('$', 		'(', 		')',	 	'%28', 		'%29');
		$good	= array('&#36;',	'&#40;',	'&#41;',	'&#40;',	'&#41;');
		return str_replace($bad, $good, $str);
	}
	
	//分解uri_string
	function _explode_segments()
	{
		foreach(explode("/", preg_replace("|/*(.+?)/*$|", "\\1", $this->uri_string)) as $val)
		{
			//安全过滤
			$val = trim($this->_filter_uri($val));
			if ($val != '')
			{
				$this->segments[] = $val;
			}
		}
	}
	//重置分解种子
	function _reindex_segments()
	{
		array_unshift($this->segments, NULL);
		array_unshift($this->rsegments, NULL);
		unset($this->segments[0]);
		unset($this->rsegments[0]);
	}
	// 获取分解值
	function segment($n, $no_result = FALSE)
	{
		return ( ! isset($this->segments[$n])) ? $no_result : $this->segments[$n];
	}
	// 路径路由分解值
	function rsegment($n, $no_result = FALSE)
	{
		return ( ! isset($this->rsegments[$n])) ? $no_result : $this->rsegments[$n];
	}
	/**
	 * 处理URI字符串
	 * example.com/user/search/name/joe/location/UK/gender/male
	 *
	 * 解析为
	 *
	 * array (
	 *			name => joe
	 *			location => UK
	 *			gender => male
	 *		 )
	 */
	function uri_to_assoc($n = 3, $default = array())
	{
	 	return $this->_uri_to_assoc($n, $default, 'segment');
	}
	/**
	 * 处理路由字符串
	 *
	 */
	function ruri_to_assoc($n = 3, $default = array())
	{
	 	return $this->_uri_to_assoc($n, $default, 'rsegment');
	}

	/**
	 * 由URI生成关联数组
	 *
	 */
	function _uri_to_assoc($n = 3, $default = array(), $which = 'segment')
	{
		if ($which == 'segment')
		{
			$total_segments = 'total_segments';
			$segment_array = 'segment_array';
		}
		else
		{
			$total_segments = 'total_rsegments';
			$segment_array = 'rsegment_array';
		}
		if ( ! is_numeric($n))
		{
			return $default;
		}
		//是否已经处理
		if (isset($this->keyval[$n]))
		{
			return $this->keyval[$n];
		}
		if ($this->$total_segments() < $n)
		{
			if (count($default) == 0)
			{
				return array();
			}
			//关联数量出错时return value
			$retval = array();
			foreach ($default as $val)
			{
				$retval[$val] = FALSE;
			}
			return $retval;
		}
		//返回需要的关联数组
		$segments = $this->$segment_array();
		$i = 0;
		$lastval = '';
		$retval  = array();
		
		foreach ($segments as $seg)
		{
			if ($i % 2)
			{
				$retval[$lastval] = $seg;
			}
			else
			{
				$retval[$seg] = FALSE;
				$lastval = $seg;
			}
			$i++;
		}
		
		if (count($default) > 0)
		{
			foreach ($default as $val)
			{
				if ( ! array_key_exists($val, $retval))
				{
					$retval[$val] = FALSE;
				}
			}
		}
		// Cache the array for reuse
		$this->keyval[$n] = $retval;
		return $retval;
	}

	/**
	 * 从一个关联数组产生 URI 字符串
	 *
	 */
	function assoc_to_uri($array)
	{
		$temp = array();
		foreach ((array)$array as $key => $val)
		{
			$temp[] = $key;
			$temp[] = $val;
		}
		return implode('/', $temp);
	}
	/**
	 * 加转义过滤
	 *
	 */
	function slash_segment($n, $where = 'trailing')
	{
		return $this->_slash_segment($n, $where, 'segment');
	}
	function slash_rsegment($n, $where = 'trailing')
	{
		return $this->_slash_segment($n, $where, 'rsegment');
	}
	function _slash_segment($n, $where = 'trailing', $which = 'segment')
	{
		if ($where == 'trailing')
		{
			$trailing	= '/';
			$leading	= '';
		}
		elseif ($where == 'leading')
		{
			$leading	= '/';
			$trailing	= '';
		}
		else
		{
			$leading	= '/';
			$trailing	= '/';
		}
		return $leading.$this->$which($n).$trailing;
	}

	function segment_array()
	{
		return $this->segments;
	}

	/**
	 * 路由数组
	 *
	 */
	function rsegment_array()
	{
		return $this->rsegments;
	}

	/**
	 * 分解的数目
	 *
	 */
	function total_segments()
	{
		return count($this->segments);
	}
	function total_rsegments()
	{
		return count($this->rsegments);
	}
	/**
	 * 返回处理的URL值
	 *
	 */
	function uri_string()
	{
		return $this->uri_string;
	}

	function ruri_string()
	{
		return '/'.implode('/', $this->rsegment_array()).'/';
	}
}
# 本程序是一个开源系统,使用时请你仔细阅读使用协议,商业用途请自觉购买商业授权.
# Copyright (C) 长沙米拓信息技术有限公司 (http://www.metinfo.cn). All rights reserved.
?>